package com.tyc.shiro.oauth2;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ssh.JschUtil;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义用于处理用户身份认证的过滤器
 *
 * @author tyc
 * @version 1.0
 * @date 2023-12-21 15:44:37
 */
public class OAuth2Filter extends AuthenticatingFilter {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    /**
     * 第二步：获取token，成功后调用 AuthorizingRealm 的 supports 方法
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        return StrUtil.isBlank(token)?null:new OAuth2Token(token);
    }

    /**
     * 第一步：在用户尝试访问受保护的资源而进行验证，通过后调用 createToken
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //获取请求token，如果token不存在，直接返回401
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
            httpResponse.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("code", HttpStatus.HTTP_UNAUTHORIZED);
            jsonObject.set("msg","invalid token");
            httpResponse.getWriter().print(JSONUtil.toJsonStr(jsonObject));

            return false;
        }
        return executeLogin(request, servletResponse);
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=utf-8");
        httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
        HttpServletRequest r = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        httpResponse.setHeader("Access-Control-Allow-Origin", r.getHeader("Origin"));
        try {
            //处理登录失败的异常
            Throwable throwable = e.getCause() == null ? e : e.getCause();
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("code", HttpStatus.HTTP_UNAUTHORIZED);
            jsonObject.set("msg",throwable.getMessage());
            httpResponse.getWriter().print(JSONUtil.toJsonStr(jsonObject));
        } catch (IOException e1) {
            logger.error("onLoginFailure", e1);
        }

        return false;
    }


}
